//
//  SelectTimeDialog.swift
//  mggz
//
//  Created by Apple on 2018/5/14.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift
import YYText

class SelectTimeDialog: UIView {
    var autoClose = true
    
    @IBOutlet var contentview: UIView!
    @IBOutlet weak var dialogview: UIView!
    
    @IBOutlet weak var titlename: UILabel!
    @IBOutlet weak var startTime: UILabel!
    @IBOutlet weak var endTime: UILabel!
    @IBOutlet weak var delbtn: UILabel!
    @IBOutlet weak var submitbtn: UILabel!
    @IBOutlet weak var closebtn: UILabel!
    
    var cancelclick:DialogCancel?
    var submitclick:DialogDataSubmit?
    
    var startTimeStr,endTimeStr:String?
    
    var emptyStr = "\n\n\n\n\n"
    
    lazy var topview:UIView = {
        var window = UIApplication.shared.keyWindow
        return (window?.subviews.last)!
    }()
    
    lazy var datePicker:UIDatePicker = {
        let datePicker = UIDatePicker.init()
        datePicker.frame = CGRect(x: 0, y: 10, width: ScreenWidth-20, height: self.getMessageHeight(self.emptyStr)*1.2)
        datePicker.locale = NSLocale.init(localeIdentifier: "zh_CN") as Locale
        datePicker.datePickerMode = .time
        //datePicker.backgroundColor = UIColor.white
        datePicker.setDate(NSDate.init() as Date, animated: true)
        datePicker.addTarget(self, action: #selector(amchangeDate(_:)), for: UIControlEvents.valueChanged)
        return datePicker
    }()
    
    lazy var actionsheet:UIAlertController = {
        var alert = UIAlertController(title: self.emptyStr, message: "", preferredStyle: .actionSheet)
        alert.view.addSubview(self.datePicker)
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        let okAction = UIAlertAction(title: "确定", style: .default, handler: { (action) in
            print("确定")
            self.startTime.text = self.startTimeStr
            self.endTime.text = self.endTimeStr
        })
        alert.addAction(cancelAction)
        alert.addAction(okAction)
        return alert
    }()
    
    //计算行高
    func getMessageHeight(_ msg:String) -> CGFloat{
        var introText = NSMutableAttributedString.init(string: msg)
        introText.yy_font = UIFont.systemFont(ofSize: 17)
        introText.yy_lineSpacing = 0
        let layout = YYTextLayout.init(containerSize: CGSize(width: ScreenWidth, height: CGFloat.greatestFiniteMagnitude), text: introText)
        return (layout?.textBoundingSize.height)!
        
    }
    
    
    
    func setClickTap(_ view:UIView){
        let t = UITapGestureRecognizer(target: self, action: #selector(click(_:)))
        t.numberOfTapsRequired = 1
        t.numberOfTouchesRequired = 1
        view.addGestureRecognizer(t)
    }
    
    @objc fileprivate func amchangeDate(_ datePicker : UIDatePicker){
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "HH:mm"
        if datePicker.tag == 0{
            self.startTimeStr = dateFormatter.string(from: datePicker.date)
            //self.startTime.text = dateFormatter.string(from: datePicker.date)
        }else{
            self.endTimeStr = dateFormatter.string(from: datePicker.date)
            //self.endTime.text = dateFormatter.string(from: datePicker.date)
        }
        
    }
    
    @objc func click(_ sender:UIGestureRecognizer){
        print("\(sender.view?.tag)")
        if sender.view?.tag == 0 || sender.view?.tag == 1{
            datePicker.tag = (sender.view?.tag)!
            //self.contentview.addSubview(datePicker)
            self.startTimeStr = self.startTime.text ?? ""
            self.endTimeStr = self.endTime.text ?? ""
            self.viewController()?.present(self.actionsheet, animated: true, completion: nil)
        }else if sender.view?.tag == 2{
            if self.cancelclick != nil{
                self.cancelclick!()
            }
            //self.datePicker.removeFromSuperview()
            self.dismiss()
            
        }else if sender.view?.tag == 3{
            if self.submitclick != nil{
                var dic = ["startTime":self.startTimeStr ?? "","endTime":self.endTimeStr ?? ""]
                self.submitclick!(dic)
            }
            //self.datePicker.removeFromSuperview()
            if self.autoClose{
                self.dismiss()
            }
            
        }else if sender.view?.tag == 4{
            //self.datePicker.removeFromSuperview()
            self.dismiss()
        }
        
        /*let datePickerManager = PGDatePickManager()
        datePickerManager.isShadeBackgroud = true
        datePickerManager.style = .style3
        let datePicker = datePickerManager.datePicker!
        datePicker.delegate = self
        datePicker.datePickerType = .type1
        datePicker.datePickerMode = .yearAndMonth*/
    }
    
    class func initWithClick(frame: CGRect,_cancelclick cancelclick:@escaping DialogCancel,_submitclick submitclick:@escaping DialogDataSubmit) -> SelectTimeDialog{
        var view = SelectTimeDialog(frame: frame)
        view.isUserInteractionEnabled = true
        view.cancelclick = cancelclick
        view.submitclick = submitclick
        return view
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setupSubviews()
    }
    
    required init?(coder aDecoder: NSCoder) {//storyboard
        super.init(coder: aDecoder)
        self.setupSubviews()
    }
    
    /*convenience init(frame: CGRect,_viewclick viewclick:@escaping (Int)->()) {
        self.init(frame: frame)
        self.setupSubviews()
        self.viewclick = viewclick
    }*/
    
    override func layoutSubviews() {
        self.startTime.isUserInteractionEnabled = true
        self.startTime.tag = 0
        self.setClickTap(self.startTime)
        
        self.endTime.isUserInteractionEnabled = true
        self.endTime.tag = 1
        self.setClickTap(self.endTime)
        
        self.delbtn.tag = 2
        self.delbtn.isUserInteractionEnabled = true
        self.setClickTap(self.delbtn)
        self.contentview.isUserInteractionEnabled = true
        
        self.submitbtn.isUserInteractionEnabled = true
        self.submitbtn.tag = 3
        self.setClickTap(self.submitbtn)
        
        self.closebtn.isUserInteractionEnabled = true
        self.closebtn.tag = 4
        self.setClickTap(self.closebtn)
    }
    
    func setupSubviews() {
        let contentView = loadViewFromNib()
        addSubview(contentView)
    }
    func loadViewFromNib() -> UIView {
        let nib = UINib(nibName: "SelectTimeDialog", bundle: nil)
        let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
        view.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
        //view.backgroundColor = UIColor(red: 100/255, green: 100/255, blue: 100/255, alpha: 0.6)
        return view
    }
    
    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        //var view = super.hitTest(point, with: event)
        if !self.contentview.isUserInteractionEnabled || self.contentview.isHidden || self.contentview.alpha <= 0.01 {
            return nil
        }
        if self.contentview.point(inside: point, with: event){
            
            for subview in self.contentview.subviews.reversed(){
                let convertedPoint = subview.convert(point, from: self.contentview)
                let hitTestView = subview.hitTest(convertedPoint, with: event)
                if hitTestView != nil{
                    return hitTestView
                }
            }
            return self.contentview
        }
        return nil
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
    }
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        
    }
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        
    }
    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        
    }

    
    func show(){
        if self.topview != nil{
            self.topview.isUserInteractionEnabled = true
            self.topview.addSubview(self)
        }
        
    }
    
    @objc func dismiss(){
        self.removeFromSuperview()
    }
    
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
